package com.zyw.weibo.data.local;

import java.util.Date;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import cn.emagsoftware.util.DateUtilities;

public final class DataBaseManager {
	
	private DataBaseManager(){}
	
	public static void setImageCache(Context context,String url,byte[] data){
		String sql = "insert into t_cache_image(url,data,create_time) values (?,?,?)";
		DataBaseOpenHelper.getInstance(context).execSQL(sql, new Object[]{url,data,DateUtilities.getFormatDate("yyyy-MM-dd HH:mm:ss")}, false);
	}
	
	public static byte[] getImageCache(Context context,String url){
		String sql = "select data from t_cache_image where url = ?";
		SQLiteDatabase db = DataBaseOpenHelper.getInstance(context).getReadableDatabase();
		Cursor cursor = null;
		try{
			cursor = db.rawQuery(sql, new String[]{url});
			if(cursor.moveToNext()) return cursor.getBlob(0);
			else return null;
		}finally{
			if(cursor != null) cursor.close();
		}
	}
	
	public static void deleteOldImageCache(Context context){
		String sql = "delete from t_cache_image where create_time < ?";
		Date preDate = new Date(new Date().getTime()-12*60*60*1000);
		DataBaseOpenHelper.getInstance(context).execSQL(sql, new Object[]{DateUtilities.getFormatDate(preDate,"yyyy-MM-dd HH:mm:ss")}, false);
	}
	
	public static void deleteAllImageCache(Context context){
		String sql = "delete from t_cache_image";
		DataBaseOpenHelper.getInstance(context).execSQL(sql, false);
	}
	
}
